import ttree from '@/components/common/TTree.vue'
import * as dutyLogService from '@/services/DutyLogService.js'
import * as organizationService from '@/services/OrganizationService'
import moment from 'moment'
import Vue from 'vue'

export default {
  props: ['id', 'dutylog', 'dialogWidth', 'orgId', 'sequence', 'page', 'orgQuery'],
  components: {
    ttree
  },
  // watch: {
  //   dutylog: function (value) {
  //
  //     if (value == 'createDuty') {
  //       this.detailsOperate = false
  //       this.title = '新建值班日志'
  //
  //     } else if (value == 'editDuty') {
  //       this.detailsOperate = false
  //       this.title = '编辑值班日志'
  //
  //     } else if (value == 'lookDuty') {
  //       this.detailsOperate = true
  //       this.title = '值班日志详情'
  //       this.getLNSum()
  //     }
  //   }
  // },
  data: function () {
    return {
      order: 1,
      adddialog: false,
      asd: true,
      form: {
        orgId: '',
        deptId: '',
        groupId: '',
        userArray: '',
        starttime: '',
        endtime: '',
        description: '',
        dailyReport: '',
        orgReport: '',
        summary: '',
        today: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate(),
        usernames: ''
      },
      lheight: '38px',
      liheight: '38px',
      htmlTitle: '值班日志',
      title: '',
      addPerson: false,
      detailsOperate: false,
      lookdetail: true,
      personList: [],
      users: [],
      groupData: [],
      printLook: true,
      num: this.id,
      /* 详情 */
      detail: {
        deptid: '',
        orgid: '',
        usernames: '',
        monitor: [],
        dutytime: [],
        weather: [{
          weather: ''
        }],
        id: '',
        createTime: '',
        needToBeDealtWith: [{
          needWith: '',
          type: 0
        }],
      },
      timeout: {},
      description: [],
      todoDetail: '',
      dheight: '688px',
      temporary: '',
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },

    }
  },
  mounted() {
    // if (this.$profile.organiza.parentId) {
    //   organizationService.findById(this.$profile.organiza.parentId).then(res => {
    //     // this.orgFlag = res
    //   })
    // }
    this.order = (this.page - 1) * 10 + this.sequence
    this.adddialog = false
    var value = this.dutylog
    if (value == 'createDuty') {
      this.detailsOperate = false
      this.title = '新建值班日志'
      this.adddialog = true
      let saveLog = localStorage.getItem('dutyLog')
      let start = new Date()
      let end = new Date(start.getTime() + 3600 * 1000 * 24 * 7)
      let yyyy = start.getFullYear()
      let mm = start.getMonth()
      let dd = start.getDate()
      let yyyye = end.getFullYear()
      let mme = end.getMonth()
      let dde = end.getDate()
      this.detail.dutytime = [new Date(yyyy, mm, dd, 8, 30), new Date(yyyye, mme, dde, 8, 30)]
      if (saveLog) {
        this.detail = JSON.parse(saveLog).detail
        this.description = JSON.parse(saveLog).description
        this.form = JSON.parse(saveLog).form
        this.form.today = new Date()
        this.$nextTick(() => {
          this.lheight = this.$refs.dH.offsetHeight + 'px'
          this.liheight = this.$refs.dH1.offsetHeight + 'px'
        })
      }
      if (this.$profile.olevel == 1) {
        this.detail.orgid = this.$profile.fullname
      } else if (this.$profile.olevel == 0) {
        this.detail.orgid = this.$profile.organiza.name
      } else if (this.$profile.olevel == 2) {
        this.detail.deptid = this.$profile.organiza.name
        organizationService.findById(this.$profile.organiza.parentId).then(res => {
          this.detail.orgid = res.name
        })
      }
    } else if (value == 'editDuty') {
      this.detailsOperate = false
      this.title = '编辑值班日志'
      this.getData()
    } else if (value == 'lookDuty') {
      this.detailsOperate = true
      this.title = '值班日志详情'
      this.getData()
    }
  },
  methods: {
    saveitself() {
      var arr = [this.form, this.detail]
      localStorage.setItem('myLog', JSON.stringify(arr))
      this.timeout = setTimeout(() => {
        this.saveitself()
      }, 60000)
    },
    close() {
      this.$router.push('/duty-log')
      this.adddialog = false
      // this.$refs.dutyInfo.lookdetail = false
      this.asd = false
    },
    getUser() {
      if (localStorage.getItem('myLog')) {
        var arr = JSON.parse(localStorage.getItem('myLog'))
        this.form = arr[0]
        this.form.today = this.$m()
        this.detail = arr[1]
        this.$nextTick(() => {
          this.lheight = this.$refs.dH.offsetHeight + 'px'
          this.liheight = this.$refs.dH1.offsetHeight + 'px'

        })
      } else {
        //         this.$axios.get(this.$config['getDutyCount'],{params:{skey:localStorage.getItem('auth')}}).then((res)=>{

        //         this.form.orgReport=res.data.content
        //   })
        this.$axios.get(this.$config['getDaO'], {params: {skey: localStorage.getItem('auth')}}).then((res) => {
          this.detail.deptid = res.data.content.deptName || ''
          this.detail.orgid = res.data.content.orgName || ''
          this.form.deptId = res.data.content.deptId || ''
          this.form.orgId = res.data.content.orgId || ''

        })
        this.$axios.get(this.$config['dutyWN'], {params: {skey: localStorage.getItem('auth')}}).then((res) => {
          if (res.data.content.weather.length == 0) {
            this.detail.weather = [{data: ''}]
          } else {
            this.detail.weather = res.data.content.weather
          }
          if (res.data.content.needToBeDealtWith.length == 0) {
            this.detail.needToBeDealtWith = [{data: ''}]
          } else {
            this.detail.needToBeDealtWith = res.data.content.needToBeDealtWith
          }

        }).then(() => {
          this.$nextTick(() => {
            this.lheight = this.$refs.dH.offsetHeight + 'px'
            this.liheight = this.$refs.dH1.offsetHeight + 'px'
            this.dheight = this.$refs.det.offsetHeight - 1 + 'px'

          })
        })

        //       this.$axios.get(this.$config['getDU'],{params:{skey:localStorage.getItem('auth')}}).then((res)=>{
        //         this.detail.usernames=res.data.content[0].names
        //             this.form.groupId=res.data.content[0].groupId
        //             this.form.userArray=res.data.content[0].userArray

        //   })
      }

    },
    // 打印
    printPage() {
      for (var i of document.head.getElementsByTagName('style')) {
        if (i.media == 'print') {
          i.innerHTML = '@page { size: portrait; }'
        }
      }
      // this.$emit('changeWidth', '790px')
      this.printLook = false
      document.getElementById('app').style.display = 'none'
      setTimeout(() => {
        window.print()
        this.$router.push('/duty-log')
        // this.$emit('changeWidth', '80%')
        document.getElementById('app').style.display = 'block'
      }, 100)
    },
    // 导出pdf
    // toPdf () {
    //   var dom = document.querySelector('#wordd')
    //   getPdf('123', dom)
    // },
    exportWord() {
      var filePath = 'd:'
      if (filePath != null) {
        try {
          var word = new ActiveXObject('Word.Application')
          var doc = word.Documents.Add('', 0, 1)
          var range = doc.Range(0, 1)
          var sel = document.body.createTextRange()
          try {
            sel.moveToElementText(content)
          } catch (notE) {
            alert('导出数据失败，没有数据可以导出。')
            window.close()
            return
          }
          sel.select()
          sel.execCommand('Copy')
          range.Paste()
          // word.Application.Visible = true;// 控制word窗口是否显示
          doc.saveAs(filePath + '/导出测试.doc') // 保存
          alert('导出成功')
        } catch (e) {
          alert('导出数据失败，需要在客户机器安装Microsoft Office Word(不限版本)，将当前站点加入信任站点，允许在IE中运行ActiveX控件。')
        } finally {
          try {
            word.quit()
          } catch (ex) {
          }
        }

      }
    },
    add() {
      this.addPerson = true
    },
    // close () {
    //   this.addPerson = false
    // },
    close1() {
      this.addPerson = false
    },
    creatsure() {
      this.addPerson = false

      var arr = []
      for (var i of this.$refs.outlan.members) {
        arr.push(i.d_id)
      }
      this.form.person = arr.join(',')
    },
    creatcancel() {
      this.addPerson = false
    },
    cancel() {
      this.close()
      this.$emit('update')
    },
    save() {
      var value = this.dutylog
      if (!this.detail.dutytime[0]) {
        this.$alert('开始时间和结束时间不能为空')
        return false
      } else {
        if (this.detail.dutytime[0] == this.detail.dutytime[1]) {
          this.$alert('开始时间和结束时间不能相同')
          return false
        }
      }
      var dutyWeatherns = this.detail.weather.map(function (item) {
        if (item.data != '') {
          return item
        }
      })
      var dutyNeeds = this.detail.needToBeDealtWith.map(function (item) {
        if (item.data != '') {
          return item
        }
      })
      let form2 = JSON.parse(JSON.stringify(this.form))
      form2.today = ''
      let obj = {detail: this.detail, description: this.description, form: form2}
      localStorage.setItem('dutyLog', JSON.stringify(obj))
      this.$message({
        type: 'success',
        message: '保存成功!'
      })
    },
    sure() {
      var value = this.dutylog
      if (!this.detail.dutytime[0]) {
        this.$alert('开始时间和结束时间不能为空')
        return false
      } else {
        if (this.detail.dutytime[0] == this.detail.dutytime[1]) {
          this.$alert('开始时间和结束时间不能相同')
          return false
        }
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      var dutyWeatherns = this.detail.weather.map(function (item) {
        if (item.weather != '') {
          return {weather: item.weather}
        }
      })
      var dutyNeeds = this.detail.needToBeDealtWith.map(function (item) {
        if (item.needWith != '') {
          return {needWith: item.needWith, type: item.type}
        }
      })
      var obj = {
        description: this.form.description,
        dutyEnd: new Date(this.detail.dutytime[1]),
        dutyName: this.form.dutyName,
        dutyNeeds,
        dutyStart: new Date(this.detail.dutytime[0]),
        dutyWeatherns,
        orgReport: this.form.orgReport,
        organiza: {id: this.$profile.organiza.id}, //  || this.$profile.organiza.id
        summary: this.form.summary,
        today: new Date(this.form.today),
        usernames: this.form.usernames
        // id: this.id
      }
      if (value == 'createDuty') {
        dutyLogService.create(obj).then(res => {
          if (res) {
            this.$message({
              type: 'success',
              message: '创建成功!'
            })
            this.cancel()
          }
          loading.close()
        })
      } else if (value == 'editDuty') {
        obj.id = this.form.id
        obj.createTime = this.form.createTime
        dutyLogService.update(obj).then(res => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          loading.close()
          this.cancel()
        })
      }
    },
    getData() {
      var that = this
      dutyLogService.searchById(this.id).then(res => {
        this.form.usernames = res.usernames
        if (res.organiza) {
          if (res.organiza.level == 0 || res.organiza.level == 1) {
            this.detail.orgid = res.organiza.name
            this.detail.deptid = ''
          } else if (res.organiza.level == 2) {
            this.detail.deptid = res.organiza.name
            organizationService.findById(res.organiza.parentId).then(res => {
              this.detail.orgid = res.name
            })
          }
        } else {
          this.detail.orgid = ''
          this.detail.deptid = ''
        }//orgid   deptid
        this.form.id = res.id
        this.form.createTime = res.createTime
        this.detail.dutytime = [res.dutyStart ? moment(res.dutyStart).format('YYYY-MM-DD HH:mm:ss') : '', res.dutyEnd ? moment(res.dutyEnd).format('YYYY-MM-DD HH:mm:ss') : '']
        this.form.dId = res.dId
        if (res.description) {
          if (this.dutylog == 'lookDuty') {
            this.description = res.description.split('\n')
          } else if (this.dutylog == 'editDuty') {
            try {
              this.form.description = JSON.parse(res.description)
            }
            catch (e) {
              this.form.description = res.description
            }
          }
        }
        if (res.dutyNeeds.length) { // needWith
          this.detail.needToBeDealtWith = res.dutyNeeds
        }
        if (res.dutyWeatherns.length) {
          this.detail.weather = res.dutyWeatherns
        }
        this.form.deptId = res.deptId || ''
        this.form.orgId = res.orgId || ''
        this.adddialog = true
      }).then(res => {
        var dutyDetail, weatherList, needList
        if (this.dutylog == 'lookDuty') {
          dutyDetail = document.querySelector('.dutyDetail')
          Vue.set(that, 'dheight', dutyDetail.clientHeight + 'px')
        }
        weatherList = document.querySelector('.weather_list')
        needList = document.querySelector('.need_list')
        Vue.set(that, 'lheight', weatherList.clientHeight + 'px')
        Vue.set(that, 'liheight', needList.clientHeight + 'px')
      })
    },
    myPerson(id) {
      this.$axios.get(this.$config['selectSchedulingUser'], {
        params: {
          skey: localStorage.getItem('auth'),
          dId: id
        }
      }).then((res) => {

        this.users = res.data.content

        //  for(var i of res.data.content){
        //    this.form.usernames=i.usernames
        //  }
      })
    },
    handleCommand(id) {
      this.myPerson(id)
    },
    groupData1() {
      var arr = []
      this.$axios.get('InsideMailListSelectInsideMailListUser', {
        params: {
          'skey': localStorage.getItem('auth')
        }

      }).then((res) => {
        arr.push({
          d_id: 1,
          name: '全部',
          users: res.data.content
        })
      }).then(() => {
        this.$axios.get(this.$config['searchALLGroup'], {
          params: {
            'skey': localStorage.getItem('auth')
          }

        }).then((res) => {
          this.groupData = arr.concat(res.data.content.innerGroup)
        })
      })
    },

    addRow() {
      this.detail.weather.push({
        'data': '',
      })
      this.$nextTick(() => {
        this.lheight = this.$refs.dH.offsetHeight + 'px'
      })
    },
    addtbRow() {
      this.detail.needToBeDealtWith.unshift({
        'data': '',
        'type': 0
      })
      this.$nextTick(() => {
        this.liheight = this.$refs.dH1.offsetHeight + 'px'
      })
    },
    delWeather(index) {
      this.detail.weather.splice(index, 1)
      this.$nextTick(() => {
        this.lheight = this.$refs.dH.offsetHeight + 'px'
      })
    },
    getLNSum(flag) {
      var that = this
      dutyLogService.search(this.order, this.orgQuery, 1).then(res => {
        if (!res.data[0]) {
          this.$message({
            type: 'warning',
            message: '已经没有下一篇了'
          })
          this.order -= 1
          return false
        }
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.form.usernames = res.data[0].usernames
        if (res.data[0].organiza) {
          if (res.data[0].organiza.level == 0 || res.data[0].organiza.level == 1) {
            this.detail.orgid = res.data[0].organiza.name
            this.detail.deptid = ''
          } else if (res.data[0].organiza.level == 2) {
            this.detail.deptid = res.data[0].organiza.name
            organizationService.findById(res.data[0].organiza.parentId).then(res => {
              this.detail.orgid = res.name
            })
          }
        } else {
          this.detail.orgid = ''
          this.detail.deptid = ''
        }//orgid   deptid
        this.detail.dutytime = [res.data[0].dutyStart ? moment(res.data[0].dutyStart).format('YYYY-MM-DD HH:mm:ss') : '', res.data[0].dutyEnd ? moment(res.data[0].dutyEnd).format('YYYY-MM-DD HH:mm:ss') : '']
        this.form.dId = res.data[0].dId
        if (res.data[0].description) {
          if (this.dutylog == 'lookDuty') {
            this.description = res.data[0].description.split('\n')
          } else if (this.dutylog == 'editDuty') {
            this.form.description = res.data[0].description
          }
        }
        if (res.data[0].dutyNeeds.length) { // needWith
          this.detail.needToBeDealtWith = res.data[0].dutyNeeds
        }
        if (res.data[0].dutyWeatherns.length) {
          this.detail.weather = res.data[0].dutyWeatherns
        }
        this.form.deptId = res.data[0].deptId || ''
        this.form.orgId = res.data[0].orgId || ''
        loading.close()
      }).then(res => {
        var dutyDetail, weatherList, needList
        dutyDetail = document.querySelector('.dutyDetail')
        Vue.set(that, 'dheight', dutyDetail.clientHeight + 'px')
        weatherList = document.querySelector('.weather_list')
        Vue.set(that, 'lheight', weatherList.clientHeight + 'px')
        needList = document.querySelector('.need_list')
        Vue.set(that, 'liheight', needList.clientHeight + 'px')
      })
    },
    lastLog() {
      this.order -= 1
      if (this.order < 0) {
        this.$message({
          type: 'warning',
          message: '已经没有上一篇了'
        })
        this.order += 1
        return false
      }
      this.getLNSum('lastLog')
    },
    nextLog() {
      this.order += 1
      this.getLNSum('nextLog')
    }
  }
}
